import json
import requests
import boto3


def lambda_handler(event, context):
    # setup

    endpoint = "https://search-restaurants-m4dtizgfgazswpzlr3kiji25wq.us-east-1.es.amazonaws.com"

    headers = {"Content-Type": "application/json"}
    username = 'tt2756'
    password = '?????'

    sqs = boto3.client('sqs')
    queue_url = 'https://sqs.us-east-1.amazonaws.com/292220080392/Q1'

    response = sqs.receive_message(QueueUrl=queue_url)

    if 'Messages' in response:
        # get parameter
        data = json.loads(response['Messages'][0]['Body'])
        cuisine = data['cuisine']
        location = data['location']
        nop = data['nop']
        date = data['date']
        time = data['time']
        phone = data['phone']

        sqs.delete_message(
            QueueUrl=queue_url,
            ReceiptHandle=response['Messages'][0]['ReceiptHandle']
        )

        # query es
        index = "restaurants"
        query = {
            "query": {
                "function_score": {
                    "query": {
                        "match": {
                            "cuisine": cuisine
                        }
                    },
                    "random_score": {}
                }
            },
            "size": 1
        }

        url = endpoint + '/' + index + '/_search'

        result = json.loads(requests.get(url, auth=(username, password), headers=headers, data=json.dumps(query)).text)
        id = result["hits"]["hits"][0]["_source"]["restaurantID"]

        # query db
        res = {}
        dynamodb = boto3.resource('dynamodb')
        table = dynamodb.Table('yelp-restaurants')
        data = table.scan()
        for item in data['Items']:
            if item['business_id'] == id:
                res = item
                break

        # send text message
        sns = boto3.client('sns')
        try:
            response = sns.publish(
                PhoneNumber='+1' + phone,
                Message='Hello! Here are my ' + cuisine + '  restaurant suggestions for ' + nop + ' people, for ' + date + ' at ' + time + ': ' +
                        res['name'] + ', located at ' + res['address'] + '. Enjoy your meal!'
            )
            return 'success ' + str(response)
        except Exception as e:
            return 'fail: ' + e
    return 'None'




